<template>
  <ElDialog
    v-model="visible"
    title="选择兑换商品"
    width="800px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="handleCancel"
  >
    <ElForm>
      <ElFormItem label="商品名称">
        <ElInput
          v-model="searchName"
          style="width: 300px"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter="handleSearch"
        />
        <ElButton type="primary" @click="handleSearch" style="margin-left: 8px">搜索</ElButton>
      </ElFormItem>
    </ElForm>
    <ElTable
      :data="goodsList"
      style="width: 100%; margin-bottom: 16px"
      :row-key="(row) => row.id"
      :height="400"
      border
      highlight-current-row
      :pagination="false"
      :show-overflow-tooltip="true"
      @row-click="handleRowClick"
      :row-class-name="tableRowClassName"
    >
      <ElTableColumn label="选择" width="60">
        <template #default="{ row }">
          <ElRadio v-model="selectedRowId" :label="row.id"></ElRadio>
        </template>
      </ElTableColumn>
      <ElTableColumn prop="scoreName" label="商品名称" min-width="150" />
      <el-table-column label="商品图片" width="120">
        <template #default="scope">
          <div v-if="scope.row.scorePhoto" class="image-preview">
            <ElImage
              :src="scope.row.scorePhoto"
              :preview-src-list="[scope.row.scorePhoto]"
              fit="cover"
              class="product-img"
              :preview-teleported="true"
            />
          </div>
          <span v-else class="text-gray-400">无图片</span>
        </template>
      </el-table-column>
      <ElTableColumn prop="scoreCnt" label="积分" width="120" />
      <ElTableColumn prop="scoreStockNum" label="库存" width="120" />
      <ElTableColumn prop="scoreUpFlag" label="状态" width="100" :formatter="formatStatus" />
    </ElTable>
    <ElPagination
      v-if="total > 0"
      :current-page="current"
      :page-size="pageSize"
      :total="total"
      layout="prev, pager, next"
      @current-change="handlePageChange"
      background
      style="margin: 16px 0; text-align: right"
    />
    <template #footer>
      <ElSpace>
        <ElButton @click="handleCancel">取消</ElButton>
        <ElButton type="primary" @click="handleConfirm">确认选择</ElButton>
      </ElSpace>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import { ref, watch, defineEmits, defineProps } from 'vue'
  import { ElMessage } from 'element-plus'
  import { scoGoodsPageDataUsingPost } from '@/api'

  const props = defineProps<{ visible: boolean }>()
  const emit = defineEmits<{
    (e: 'update:visible', v: boolean): void
    (e: 'confirm', row: any): void
  }>()

  const visible = ref(props.visible)
  watch(
    () => props.visible,
    (v) => (visible.value = v)
  )
  watch(visible, (v) => emit('update:visible', v))

  const searchName = ref('')
  const goodsList = ref<any[]>([])
  const selectedRow = ref<any | null>(null)
  const selectedRowId = ref<number | null>(null)
  const current = ref(1)
  const pageSize = ref(10)
  const total = ref(0)

  const handleSearch = async () => {
    try {
      const res = await scoGoodsPageDataUsingPost({
        body: {
          current: current.value,
          size: pageSize.value,
          scoreName: searchName.value || undefined,
          scoreUpFlag: 2 // 只查上架商品
        }
      })
      const list = res && Array.isArray(res.list) ? res.list : []
      goodsList.value = list
      total.value = res?.total || 0
    } catch (err: any) {
      console.error(err)
      ElMessage.error('商品获取失败')
    }
  }

  const handlePageChange = (p: number) => {
    current.value = p
    handleSearch()
  }

  const handleRowClick = (row: any) => {
    selectedRow.value = row
    selectedRowId.value = row.id
  }

  watch(selectedRowId, (id) => {
    if (id == null) {
      selectedRow.value = null
      return
    }
    const found = goodsList.value.find((item) => item.id === id)
    selectedRow.value = found || null
  })

  const tableRowClassName = ({ row }: { row: any }) => {
    return selectedRowId.value === row.id ? 'selected-row' : ''
  }

  const handleConfirm = () => {
    if (!selectedRow.value) {
      ElMessage.warning('请选择一个商品')
      return
    }
    emit('confirm', selectedRow.value)
    visible.value = false
  }

  const handleCancel = () => {
    visible.value = false
  }

  const formatStatus = (row: any) => {
    return row.scoreUpFlag === 2 ? '上架' : '下架'
  }

  // 初始化加载
  handleSearch()
</script>

<style lang="scss" scoped>
  /* 可根据项目风格调整 */
  .selected-row {
    background-color: #e6f7ff !important;
  }

  :deep .el-radio__label {
    display: none !important;
  }

  .image-preview {
    .product-img {
      width: 60px;
      height: 60px;
      cursor: pointer;
      object-fit: cover;
      border-radius: 4px;
    }

    .view-product-img {
      max-width: 300px;
      max-height: 300px;
      object-fit: cover;
      border-radius: 4px;
    }
  }
</style>
